using Admin2025.Application.Dtos;
using Admin2025.Application.IServices;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Admin2025.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
[Authorize(Roles = "SuperAdmin")] // 仅超级管理员可访问
public class RoleManagementController : ControllerBase
{
  private readonly IRoleManagementService _roleService;

  public RoleManagementController(IRoleManagementService roleService)
  {
    _roleService = roleService;
  }

  [HttpPost("assign-role")]
  public async Task<IActionResult> AssignRole([FromBody] AssignRoleDto dto)
  {
    var ok = await _roleService.AssignRoleToUserAsync(dto.UserId, dto.RoleId);
    return ok ? Ok() : BadRequest("Failed to assign role.");
  }

  [HttpPost("remove-role")]
  public async Task<IActionResult> RemoveRole([FromBody] AssignRoleDto dto)
  {
    var ok = await _roleService.RemoveRoleFromUserAsync(dto.UserId, dto.RoleId);
    return ok ? Ok() : BadRequest("Failed to remove role.");
  }

  [HttpPost("create-role")]
  public async Task<IActionResult> CreateRole([FromBody] CreateRoleDto dto)
  {
    var ok = await _roleService.CreateRoleAsync(dto);
    return ok ? Ok() : BadRequest("Role already exists.");
  }

  [HttpPut("update-role/{roleId}")]
  public async Task<IActionResult> UpdateRole(Guid roleId, [FromBody] UpdateRoleDto dto)
  {
    var ok = await _roleService.UpdateRoleAsync(roleId, dto);
    return ok ? Ok() : NotFound("Role not found.");
  }

  [HttpDelete("delete-role/{roleId}")]
  public async Task<IActionResult> DeleteRole(Guid roleId)
  {
    var ok = await _roleService.DeleteRoleAsync(roleId);
    return ok ? Ok() : NotFound("Role not found.");
  }

  [HttpPost("assign-permission")]
  public async Task<IActionResult> AssignPermission([FromBody] AssignPermissionDto dto)
  {
    var ok = await _roleService.AssignPermissionToRoleAsync(dto.RoleId, dto.PermissionId);
    return ok ? Ok() : BadRequest("Failed to assign permission.");
  }

  [HttpPost("remove-permission")]
  public async Task<IActionResult> RemovePermission([FromBody] AssignPermissionDto dto)
  {
    var ok = await _roleService.RemovePermissionFromRoleAsync(dto.RoleId, dto.PermissionId);
    return ok ? Ok() : BadRequest("Failed to remove permission.");
  }
}